package so.shanku.essential.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.widget.*;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.umeng.socialize.bean.SocializeConfig;
import com.umeng.socialize.sso.UMSsoHandler;
import net.tsz.afinal.annotation.view.ViewInject;
import net.tsz.afinal.json.JsonMap;
import net.tsz.afinal.json.JsonParseHelper;
import so.shanku.essential.R;
import so.shanku.essential.activity.base.BaseActivity;
import so.shanku.essential.adapter.LeftMenuCheckboxAdapter;
import so.shanku.essential.adapter.RelationProductAdapter;
import so.shanku.essential.app.MyApplication;
import so.shanku.essential.getdata.*;
import so.shanku.essential.utils.*;
import so.shanku.essential.view.GridViewNoScroll;
import so.shanku.essential.view.ScalRefreshScrollView;
import so.shanku.essential.view.WebViewNoScroll;

import java.util.*;

/**
 * Created by Jaelyn on 2015/9/16 0016.
 * 商城专题详情
 */
public class SpecialSubjectCommonActivity extends BaseActivity {

    /**
     * 刷新的
     */
    @ViewInject(id = R.id.ptr_scrollview)
    private ScalRefreshScrollView ptr_scrollview;
    @ViewInject(id = R.id.xgv)
    private GridViewNoScroll shop_goods_xgv;
    @ViewInject(id = R.id.content_info_layout)
    private LinearLayout content_info_layout;

    /**
     * 顶部布局
     */
    @ViewInject(id = R.id.title_layout)
    private RelativeLayout title_layout;//
    /**
     * head view
     */
    @ViewInject(id = R.id.all_layout_back, click = "back_iv_click")
    private ImageView back_iv;//
    @ViewInject(id = R.id.left_menu_iv, click = "filter_iv_click")
    private ImageView filter_iv;//
    @ViewInject(id = R.id.head_title)
    private TextView head_title;//

    @ViewInject(id = R.id.search_iv, click = "search_iv_click")
    private ImageView search_iv;//
    @ViewInject(id = R.id.shoppingCart_iv, click = "shoppingCart_iv_click")
    private ImageView shoppingCart_iv;//
    @ViewInject(id = R.id.more_iv, click = "more_iv_click")
    private ImageView more_iv;//


    /**
     * head view
     */
    @com.lidroid.xutils.view.annotation.ViewInject(R.id.shop_bg_iv)
    private ImageView shop_bg_iv;//主题图片
    @com.lidroid.xutils.view.annotation.ViewInject(R.id.shop_name_tv)
    private TextView shop_name_tv;//主题
    @com.lidroid.xutils.view.annotation.ViewInject(R.id.shop_discri_tv)
    private TextView shop_discri_tv;//主题描述
    @com.lidroid.xutils.view.annotation.ViewInject(R.id.shop_detail_discri_tv)
    private TextView shop_detail_discri_tv;//店铺的描述

    /**
     * 显示商品标志
     */
    @com.lidroid.xutils.view.annotation.ViewInject(R.id.all_product_layout)
    private LinearLayout all_product_layout;


    /**
     * 网页加载精选描述
     */
    @com.lidroid.xutils.view.annotation.ViewInject(R.id.theme_descri_web_layout)
    private LinearLayout theme_descri_web_layout;
    @com.lidroid.xutils.view.annotation.ViewInject(R.id.theme_descri_web)
    private WebViewNoScroll theme_descri_web;//详情介绍

    /**
     * 侧滑抽屉
     */
    @ViewInject(id = R.id.drawer_layout)
    private DrawerLayout drawer_layout;
    @ViewInject(id = R.id.left_drawer)
    private LinearLayout left_drawer;
    /**
     * 分类
     */
    @ViewInject(id = R.id.classfy_layout)
    private LinearLayout classfy_layout;
    @ViewInject(id = R.id.classfy_lv)
    private ListView classfy_lv;
    /**
     * 品牌
     */
    @ViewInject(id = R.id.brand_layout)
    private LinearLayout brand_layout;
    @ViewInject(id = R.id.brand_lv)
    private ListView brand_lv;

    @ViewInject(id = R.id.btn_cancel, click = "btn_cancel_click")
    private Button btn_cancel;

    @ViewInject(id = R.id.btn_confirm, click = "btn_confirm_click")
    private Button btn_confirm;

    /**
     * 商品大分类的id
     */
    private String categoryId;
    /**
     * 对的品牌 侧滑需要
     */
    private ArrayList<JsonMap<String, Object>> brandsList = new ArrayList<JsonMap<String, Object>>();
    /**
     * 侧边栏选中的数据
     */
    private ArrayList<JsonMap<String, Object>> selectBrandsList = new ArrayList<JsonMap<String, Object>>();

    /**
     * 二级分类
     */
    private ArrayList<JsonMap<String, Object>> classfyList = new ArrayList<JsonMap<String, Object>>();
    /**
     * 侧边栏选中的数据
     */
    private ArrayList<JsonMap<String, Object>> selectClassfyList = new ArrayList<JsonMap<String, Object>>();
    /**
     * 商品
     */
    private ArrayList<JsonMap<String, Object>> dataList = new ArrayList<JsonMap<String, Object>>();
    private RelationProductAdapter relationProductAdapter;

    private int nPage = 0;

    private JsonMap brandDatas; //店铺信息
    private boolean isCollected;//是否已收藏

    /**
     * 请求类型,0:专栏,1:店铺
     */
    private int flag = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.special_subject_detail_layout);
        addHeadView();
        filter_iv.setVisibility(View.VISIBLE);
        categoryId = getIntent().getStringExtra(Constant.ID);
        flag = getIntent().getIntExtra(ExtraKeys.Key_Msg1, 0);
        if (flag == 0) {
            String formartStr = GetDataConfing.Url_Base + "FindBrand/AppFindBrandDetai?userId=%s&disId=%s";
            String url = String.format(formartStr, Utils.getUserId(mContext), categoryId);
            theme_descri_web.loadUrl(url);
            theme_descri_web_layout.setVisibility(View.VISIBLE);
            all_product_layout.setVisibility(View.GONE);
        } else if (flag == 1) {
            theme_descri_web_layout.setVisibility(View.GONE);
            all_product_layout.setVisibility(View.VISIBLE);
        }
        getThemeDetail();
        getServiceData(true);
    }

    private LeftMenuCheckboxAdapter leftBrandMenuCheckboxAdapter;
    private LeftMenuCheckboxAdapter leftClassfyMenuCheckboxAdapter;

    /**
     * 打开侧边拉
     */
    private void showLeftData() {
        if (brandsList.size() == 0) {
            brand_layout.setVisibility(View.GONE);
        } else {
            leftBrandMenuCheckboxAdapter = new LeftMenuCheckboxAdapter(mContext, brandsList);
            brand_lv.setAdapter(leftBrandMenuCheckboxAdapter);
        }

        if (classfyList.size() == 0) {
            classfy_layout.setVisibility(View.GONE);
        } else {
            leftClassfyMenuCheckboxAdapter = new LeftMenuCheckboxAdapter(mContext, classfyList);
            classfy_lv.setAdapter(leftClassfyMenuCheckboxAdapter);
        }
    }

    /**
     * 确定按钮点击
     *
     * @param view
     */
    public void btn_confirm_click(View view) {
        selectBrandsList.clear();
        selectClassfyList.clear();
        if (!brandsList.isEmpty()) {
            brandsList = (ArrayList<JsonMap<String, Object>>) leftBrandMenuCheckboxAdapter.getDatas();
            for (int i = 0; i < brandsList.size(); i++) {
                JsonMap jsonMap = brandsList.get(i);
                if (jsonMap.getBoolean("isChecked")) {
                    selectBrandsList.add(jsonMap);
                }
            }
        }

        if (!classfyList.isEmpty()) {
            classfyList = (ArrayList<JsonMap<String, Object>>) leftClassfyMenuCheckboxAdapter.getDatas();
            for (int i = 0; i < classfyList.size(); i++) {
                JsonMap jsonMap = classfyList.get(i);
                if (jsonMap.getBoolean("isChecked")) {
                    selectClassfyList.add(jsonMap);
                }
            }
        }
        drawer_layout.closeDrawer(left_drawer);
        getServiceData(true);
    }

    /**
     * 取消按钮点击
     *
     * @param view
     */
    public void btn_cancel_click(View view) {
        drawer_layout.closeDrawer(left_drawer);
    }

    /**
     * 添加头部
     */
    private void addHeadView() {
        View headView = getLayoutInflater().inflate(R.layout.shop_theme_common_head_layout, null);
        ViewUtils.inject(this, headView);
        content_info_layout.addView(headView, 0);
        ptr_scrollview.setOnRefreshListener(loadMoreListener);
        relationProductAdapter = new RelationProductAdapter(this);
        relationProductAdapter.setDatas(dataList);
        shop_goods_xgv.setAdapter(relationProductAdapter);
        shop_goods_xgv.setOnItemClickListener(onItemClickListener);
        ptr_scrollview.setImageView(shop_bg_iv);
        setWebViewFeature();
    }

    private void setWebViewFeature() {
        WebSettings webSettings = theme_descri_web.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setAllowFileAccess(true);
        webSettings.setAllowContentAccess(true);
        webSettings.setAppCacheEnabled(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setGeolocationEnabled(true);
        webSettings.setLoadsImagesAutomatically(true);
        webSettings.setEnableSmoothTransition(true);
        webSettings.setBuiltInZoomControls(true);
        webSettings.setLightTouchEnabled(true);
        webSettings.setSupportZoom(true);
        theme_descri_web.setHapticFeedbackEnabled(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);

    }

    /**
     * item的点击
     */
    AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            JsonMap jsonmap = dataList.get(position);
            String goodsId = jsonmap.getStringNoNull("productId");
            seeProductDetail(goodsId);
        }
    };

    /**
     * 刷洗监听
     */
    private PullToRefreshBase.OnRefreshListener2 loadMoreListener = new PullToRefreshBase.OnRefreshListener2<ScrollView>() {
        @Override
        public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
            ptr_scrollview.onRefreshComplete();
        }

        @Override
        public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
            getServiceData(false);
        }
    };


    /**
     * 获取活动详情    {VendorId:12,UserInfoId:123}
     */
    private void getThemeDetail() {
        loadingToast.show();
        Map<String, Object> params = new HashMap<String, Object>();
        GetDataQueue queue = new GetDataQueue();
        if (Utils.isHasLogin(this)) {
            params.put("userId", Utils.getUserId(mContext));
        }
        params.put("themeId", categoryId);
        if (flag == 0) {
            queue.setActionName(GetDataConfing.GetAction_GetCommonThemeDetail);
        } else {
            queue.setActionName(GetDataConfing.GetAction_GetVendorDetails);
        }
        queue.setWhat(GetDataConfing.What_GetCommonThemeDetail);
        queue.setParamsNoJson(params);
        queue.setCallBack(callBack);

        getDataUtil.getData(queue);
    }

    /**
     * 获取商品  {VendorId:165,TypeId:2,currentPage:1,pageSize:10}
     */
    private void getServiceData(boolean chearAllData) {
        if (chearAllData) {
            nPage = 0;
            ptr_scrollview.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
        }
        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("themeId", categoryId);
        params.put("searchKey", "");
        params.put("productClassfyList", selectClassfyList);
        params.put("brandList", selectBrandsList);
        params.put("nPage", nPage + 1);
        GetDataQueue queue = new GetDataQueue();
        if(flag==0) {
            queue.setActionName(GetDataConfing.GetAction_GetThemeRelationGoods);
        } else if (flag==1) {
            queue.setActionName(GetDataConfing.GetAction_SelectVendorProductList);
        }
        queue.setParamsNoJson(params);
        queue.setCallBack(callBack);
        queue.setWhat(GetDataConfing.What_GetThemeRelationGoods);
        getDataUtil.getData(queue);
    }


    private IGetServicesDataCallBack callBack = new IGetServicesDataCallBack() {

        @Override
        public void onLoaded(GetDataQueue entity) {
            if (entity.isOk()) {
                if (ShowGetDataError.isCodeSuccess(mContext, entity.getInfo())) {
                    if (entity.what == GetDataConfing.What_GetThemeRelationGoods) {
                        ptr_scrollview.onRefreshComplete();
                        ArrayList<JsonMap<String, Object>> data_server = (ArrayList<JsonMap<String, Object>>) JsonParseHelper.getJsonMap_List_JsonMap(entity.getInfo(), JsonKeys.Key_Info);
                        setData(data_server);
                        validateData(data_server);
                    } else if (entity.what == GetDataConfing.What_GetCommonThemeDetail) {
                        try {
                            JsonMap goodsDatas = JsonParseHelper.getJsonMap_JsonMap(entity.getInfo(), JsonKeys.Key_Info);
                            refreshShopDetail(goodsDatas);
                        } catch (Exception e) {
                            e.printStackTrace();
                            toast.showToast(R.string.server_error);
                            finish();
                        }

                    } else if (entity.what == GetDataConfing.What_CollectionProductTheme) { //点赞
                        JsonMap<String, Object> data = JsonParseHelper.getJsonMap_JsonMap(entity.getInfo(), JsonKeys.Key_Info);
                        isCollected = data.getBoolean("isCollected");
                        toast.showToast(data.getStringNoNull("msg"));
                    }
                } else {
                    if (entity.what == GetDataConfing.What_GetThemeRelationGoods) {
                        ptr_scrollview.onRefreshComplete();
                    }
                }
            } else {
                if (entity.what == GetDataConfing.What_GetThemeRelationGoods) {
                    ptr_scrollview.onRefreshComplete();
                }
                ShowGetDataError.showNetError(mContext);
            }
            loadingToast.dismiss();
        }

    };

    /**
     * 设置主题信息 并请求相关商品的信息
     *
     * @param goodsDatas
     */
    private void refreshShopDetail(JsonMap goodsDatas) {
        isCollected = goodsDatas.getBoolean("isCollected");
        head_title.setText(goodsDatas.getStringNoNull("themeCatgoryName"));
        brandDatas = goodsDatas;
        brandsList = (ArrayList<JsonMap<String, Object>>) brandDatas.getList_JsonMap("brandList");
        classfyList = (ArrayList<JsonMap<String, Object>>) brandDatas.getList_JsonMap("productClassfyList");
        String backGroundImage = goodsDatas.getStringNoNull("backGroundImage");   //背景大图
        ImageLoader.getInstance().displayImage(backGroundImage, shop_bg_iv, MyApplication.getInstance().getShopBgOption(), new ImageLoaderBitmapCallBack());
        shop_name_tv.setText(goodsDatas.getStringNoNull("themeName"));
        shop_discri_tv.setText(goodsDatas.getStringNoNull("themeTitle"));
        if (flag == 0) {
            shop_discri_tv.setVisibility(View.GONE);
        } else if (flag == 1) {
            shop_discri_tv.setVisibility(View.VISIBLE);
            shop_detail_discri_tv.setText(goodsDatas.getStringNoNull("themeDescri"));
        }
        showLeftData();
    }


    private void setData(ArrayList<JsonMap<String, Object>> data_server) {
        if (nPage == 0) {
            dataList = data_server;
            relationProductAdapter = new RelationProductAdapter(this);
            relationProductAdapter.setShowDiscri(true);
            relationProductAdapter.setDatas(data_server);
            shop_goods_xgv.setAdapter(relationProductAdapter);
        } else {
            dataList.addAll(data_server);
            relationProductAdapter.notifyDataSetChanged();
        }
        nPage++;
    }


    /**
     * 校验数据 显示无数据等
     *
     * @param data_server
     */
    private void validateData(List<JsonMap<String, Object>> data_server) {
        if (data_server.size() == 0) {
            ptr_scrollview.setMode(PullToRefreshBase.Mode.MANUAL_REFRESH_ONLY); //下拉刷新
        } else {
            ptr_scrollview.setMode(PullToRefreshBase.Mode.PULL_FROM_END); //下拉刷新
        }
    }

    /**
     * 店铺详情介绍
     * @param view
     */
    @OnClick(R.id.shop_detail_discri_tv)
    public void shop_detail_discri_tv_click(View view) {
        Intent intent = new Intent(mContext, ShopIntroductionActivity.class);
        intent.putExtra(ExtraKeys.Key_Msg1, brandDatas.getStringNoNull("shopId"));
        jumpTo(intent);
    }

    public void back_iv_click(View view) {
        finish();
    }

    /**
     * 分享的点击事件
     *
     * @param view
     */
    public void share_iv_click(View view) {
        String shareLogo = brandDatas.getStringNoNull("backGroundImage");
        String shareTitle = brandDatas.getStringNoNull("themeCatgoryName") + "|" + brandDatas.getStringNoNull("themeTitle");
        String shareContent = brandDatas.getStringNoNull("themeDescri");
        String shareUrl = "ShopMall/Index?vid=" + categoryId;

        MyApplication.getInstance().showShareCompont(mContext, shareLogo, shareUrl, shareTitle, shareContent);
    }

    /**
     * 筛选
     *
     * @param view
     */
    public void filter_iv_click(View view) {
        if (drawer_layout.isDrawerVisible(left_drawer)) {
            drawer_layout.closeDrawer(left_drawer);
        } else {
            drawer_layout.openDrawer(left_drawer);
        }
    }

    /**
     * 搜索点击
     *
     * @param view
     */
    public void search_iv_click(View view) {
        jumpToSearchProduct();
    }


    /**
     * 购物车
     *
     * @param view
     */
    public void shoppingCart_iv_click(View view) {
        jumpToShopCart();
    }

    /**
     * 更多
     *
     * @param view
     */
    /**
     * 所有评论
     *
     * @param view
     */
    public void more_iv_click(View view) {
        showPopWindowView();
    }

    /**
     * 收藏文章
     */
    private void collect_tv_click() {
        if (Utils.isFastClick()) {
            return;
        }
        if (Utils.isHasLogin(mContext)) {
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("userId", Utils.getUserId(this));
            params.put("themeId", categoryId);
            GetDataQueue queue = new GetDataQueue();
            queue.setActionName(GetDataConfing.GetAction_CollectionProductTheme);
            queue.setParamsNoJson(params);
            queue.setCallBack(callBack);
            queue.setWhat(GetDataConfing.What_CollectionProductTheme);
            getDataUtil.getData(queue);
        } else {
            gotoLogin();
        }
    }

    public PopupWindow popupWindow;
    private TextView collect_tv;
    private TextView share_tv;
    private TextView cancel_tv;

    private void showPopWindowView() {
        if (popupWindow == null) {
            View view = getLayoutInflater().inflate(R.layout.artical_more_menu, null);
            popupWindow = new PopupWindow(view,
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT);
            popupWindow.setContentView(view);
            popupWindow.setAnimationStyle(R.style.popupAnimation);
            collect_tv = (TextView) view.findViewById(R.id.collect_tv);
            share_tv = (TextView) view.findViewById(R.id.share_tv);
            cancel_tv = (TextView) view.findViewById(R.id.cancel_tv);
            if (isCollected) {
                collect_tv.setText(R.string.cancel_collection);
            }
            View select_v = view.findViewById(R.id.select_v);
            collect_tv.setOnClickListener(myclick);
            share_tv.setOnClickListener(myclick);
            select_v.setOnClickListener(myclick);
            cancel_tv.setOnClickListener(myclick);
            popupWindow.showAtLocation(more_iv, Gravity.NO_GRAVITY, 0, 0);

        } else if (!popupWindow.isShowing()) {
            popupWindow.showAtLocation(more_iv, Gravity.NO_GRAVITY, 0, 0);
        }
    }


    /**
     * “我的”点击事件
     */
    View.OnClickListener myclick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int id = v.getId();
            popupWindow.dismiss();
            switch (id) {
                case R.id.share_tv:
                    share_iv_click(v);
                    break;
                case R.id.collect_tv:
                    collect_tv_click();
                    break;
                case R.id.select_v:
                    break;
                case R.id.cancel_tv:
                    //退出登录
                    break;

                default:
                    break;
            }
        }
    };


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**使用SSO授权必须添加如下代码 */
        UMSsoHandler ssoHandler = SocializeConfig.getSocializeConfig().getSsoHandler(requestCode);
        if (ssoHandler != null) {
            ssoHandler.authorizeCallBack(requestCode, resultCode, data);
        }
    }

}